/**
 * related to categoryCell.ui
 * 
 * @Author : chenglm
 * @Timestamp : 2016-12-28
 */
var app = sm("do_App");
var page = sm("do_Page");
var root=ui("$");
var nf = sm("do_Notification");
var openHelper = require("helper/open");
var httpSilence = require("helper/httpSilence");
var mallUrl = require("url/mall");
var listdataTabs = mm("do_ListData");
var aLayout_goCateGrid = ui("aLayout_goCateGrid");

var do_SegmentView_1 = ui("do_SegmentView_1");
var gridView_second = ui("gridView_second");
var griddata = mm("do_ListData");
gridView_second.bindItems(griddata);

root.setMapping({
	"do_SegmentView_1.tag":"categoryList"
});
var jsonTabs = [];
var jsonTabs2 = [];
root.on("dataRefreshed", function(){
	if (jsonTabs.length ==0) {
		jsonTabs = JSON.parse(do_SegmentView_1.tag);
		listdataTabs.removeAll();
		listdataTabs.addData(jsonTabs);
		do_SegmentView_1.bindItems(listdataTabs);
		do_SegmentView_1.refreshItems();
	}
});

page.on("ShopListSelectOneTab", function(data){
	var _selectedIndex=-1;
	for(var i=0; i<jsonTabs.length;i++){
		if (jsonTabs[i].categoryId == data.categoryId){
			_selectedIndex =i;
			listdataTabs.updateOne(i, 
				{
				    name : jsonTabs[i].name,
				    selected : "1",
				    categoryId : jsonTabs[i].categoryId
				}
			);
		}
		else{
			listdataTabs.updateOne(i, 
				{
				    name : jsonTabs[i].name,
				    selected : "2",
				    categoryId : jsonTabs[i].categoryId
				}
			);
		}
	}
	//do_SegmentView_tabs重新绑定数据
	do_SegmentView_1.refreshItems();
	//移动当选中的cell上
	if (_selectedIndex >=0)	{
		do_SegmentView_1.index = _selectedIndex;	
	}
	if (data.categoryId == '') {
		//gridView_second.items = [];
		griddata.removeAll();
		gridView_second.refreshItems();
		jsonTabs2 = [];
	} else {
		httpSilence.post(mallUrl.url.shopCategory.childrenListForPage, {parentId:data.categoryId}, function(data) {
			jsonTabs2 = data.childrenList;
			griddata.removeAll();
			griddata.addData(jsonTabs2);
			gridView_second.refreshItems();
			//gridView_second.items = data.childrenList;
		});
	}
	page.fire("getCategoryIdToShopList", {categoryId:data.categoryId});
});
page.on("ShopListSelectOneTab2", function(data){
	var _selectedIndex=-1;
	for(var i=0; i<jsonTabs2.length;i++){
		if (jsonTabs2[i].categoryId == data.categoryId){
			_selectedIndex =i;
			griddata.updateOne(i, 
				{
				    name : jsonTabs2[i].name,
				    selected : "1",
				    categoryId : jsonTabs2[i].categoryId
				}
			);
		}
		else{
			griddata.updateOne(i, 
				{
				    name : jsonTabs2[i].name,
				    selected : "2",
				    categoryId : jsonTabs2[i].categoryId
				}
			);
		}
	}
	page.fire("getCategoryIdToShopList", {categoryId:data.categoryId});
	gridView_second.refreshItems();
});
//显示全部
aLayout_goCateGrid.on("touch", function(){
	page.fire("ShopListRefreshCategory", listdataTabs);
	page.fire("ShopListShowAllCategory");
});